package csc.fresher.controller;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.context.SecurityContextImpl;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.codec.Base64;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.Validator;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MaxUploadSizeExceededException;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import csc.fresher.bankservice.BankService;
import csc.fresher.customannotation.UniqueLoginIdValidator;
import csc.fresher.domain.Role;
import csc.fresher.domain.Status;
import csc.fresher.domain.UserInfo;
import csc.fresher.domain.json.UserTemp;

@Controller
@RequestMapping(value = "/profile")
public class ProfileController {

	@Autowired
	private BankService bankService;

	@ModelAttribute("usertempnew")
	private UserTemp contructUserTemp() {
		return new UserTemp();
	}

	@RequestMapping
	public String goProfile(Model model) {
		Authentication auth = SecurityContextHolder.getContext()
				.getAuthentication();
		String loginId = auth.getName();
		UserInfo user = bankService.getUserInfo(loginId);
		if (user.getImage() != null) {
			byte[] encoded = Base64.encode(user.getImage());
			String encodedString = new String(encoded);
			model.addAttribute("avatar", encodedString);
		}
		model.addAttribute("user", user);
		HomeController.page = "profile";
		return "profile";
	}

	@RequestMapping(value = "/update", method = RequestMethod.POST)
	public String updateUser(
			Model model,
			final RedirectAttributes attrs,
			@Valid @ModelAttribute("usertempnew") UserTemp userTemp,
			BindingResult rs,
			@RequestParam(value = "fileUpload", required = false) MultipartFile file,
			@RequestParam(value = "passwordNew", required = false) String passwordNew,
			@RequestParam(value = "passwordNewAgain", required = false) String passwordNewAgain) {

		if (rs.hasErrors()) {
			attrs.addFlashAttribute("message", "Something wrong");
			return "redirect:/profile";
		}
		
		if(!passwordNew.equals(passwordNewAgain)){
			attrs.addFlashAttribute("message", "Password and password again must the same");
			return "redirect:/profile";
		}
		
		if (!passwordNew.equals("")) {
			userTemp.setPassword(bankService.hashPasswordSHA(passwordNew));
		}

		if (!file.isEmpty()) {
			byte[] image = null;
			try {
				image = file.getBytes();
			} catch (IOException e) {
				e.printStackTrace();
			}
			userTemp.setImage(image);
		}

		if (file.getOriginalFilename().equals("")) {
			Authentication auth = SecurityContextHolder.getContext()
					.getAuthentication();
			String loginId = auth.getName();
			UserInfo user = bankService.getUserInfo(loginId);
			userTemp.setImage(user.getImage());
		}

		Role role = bankService.getRole(userTemp.getRoleId());
		Status status = bankService.getStatus(userTemp.getStatusId());

		UserInfo userinfo = new UserInfo(userTemp.getId(), userTemp.getLoginId(), status, role,
				userTemp.getPassword(), userTemp.getCardnumberid(),
				userTemp.getFirstname(), userTemp.getLastname(),
				userTemp.getMidname(), userTemp.getPhone1(),
				userTemp.getPhone2(), userTemp.getAddress1(),
				userTemp.getAddress2(), userTemp.getEmail1(),
				userTemp.getEmail2(), userTemp.getImage());

		bankService.update(userinfo);

		attrs.addFlashAttribute("message", "Update Successfully");
		return "redirect:/profile";
	}

}
